#!/usr/bin/python3
# -*- coding: utf-8 -*-

from sqlalchemy import (
    MetaData, Table, Column, ForeignKey,
    Integer, Float, String, DateTime, Boolean, Text, func
)
from sqlalchemy import create_engine, MetaData
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from settings import config

Base = declarative_base()
DSN = "sqlite:///{db_file}?check_same_thread=False"

def create_tables():
    global engine
    Base.metadata.create_all(engine)

def create_session():
    global engine
    # engine是2.2中创建的连接
    Session = sessionmaker(bind=engine)
    # 创建Session类实例
    session = Session()
    return session
def init_db():
    global engine
    # conf = {'db_file': 'data.db'}
    conf = config['sqlite']
    db_url = DSN.format(**conf)
    # engine = create_engine(db_url)
    engine = create_engine(db_url, echo=True)

class Fdfs(Base):
    __tablename__='Fdfs'

    id = Column(Integer, primary_key=True)
    group_name = Column(String(20))
    filename = Column(String(100))
    file_id =  Column(String(100))
    status = Column(Boolean)
    size = Column(Float())
    ip = Column(String(50))
    path = Column(String(512))
    referer = Column(String(512))
    content_type = Column(String(20))
    download_count = Column(Integer)
    created_at = Column(DateTime, default=datetime.now())
    updated_at = Column(DateTime)

    def __repr__(self):
        return "[Fdfs(id='%s', group_name='%s', filename='%s', file_id='%s', status='%s', size='%s', ip='%s', path='%s', referer='%s', content_type='%s', download_count='%s', created_at='%s', updated_at='%s')]" % (self.id, self.group_name, self.filename, self.file_id, self.status, self.size, self.ip, self.path, self.referer, self.content_type, self.download_count, self.created_at, self.updated_at)
    # 单个对象方法2
    def single_to_dict(self):
        return {c.name: getattr(self, c.name) for c in self.__table__.columns}
        
    # 多个对象
    def dobule_to_dict(self):
        result = {}
        for key in self.__mapper__.c.keys():
            if getattr(self, key) is not None:
                result[key] = str(getattr(self, key))
            else:
                result[key] = getattr(self, key)
        return result

def sample_data(session):
    session.add_all(
        [Fdfs(status=True, filename='/root', content_type='d')]
    )
    session.commit()

if __name__ == '__main__':
    init_db()
    create_tables()
    session = create_session()
    sample_data(session)